package com.qianxx.base;

import android.content.Context;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import com.qianxx.base.utils.LogUtil;

import java.util.ArrayList;
import java.util.List;

public abstract class MyAdapter<T,V extends MyAdapter.ViewHolder> extends BaseAdapter{

	protected BaseAty mContext;
	protected LayoutInflater mInflater;
	protected List<T> data = new ArrayList<T>();
	private boolean ifPressed; // 为避免快速点击
	private MyListener<T> lis; // 点击监听

	public MyAdapter(Context context) {
		this.mContext = (BaseAty) context;
		mInflater = LayoutInflater.from(context);
	}

	public MyAdapter(Context context, List<T> list) {
		this.mContext = (BaseAty) context;
		mInflater = LayoutInflater.from(context);
		data.addAll(list);
	}
	
	public void setData(List<T> list) {
		data.clear();
		data.addAll(list);
		this.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		V holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(getLayoutId(),
					null);
			holder = findViewHolder(convertView);
			convertView.setTag(holder);
		} else {
			holder = (V) convertView.getTag();
		}
//
		setViewDisplay(position, data.get(position), holder);
		setClickListener(position, data.get(position), holder);
		return convertView;
	}
	/**
	 * 初始化view
	 * @param view
	 * @return
	 */
	protected abstract V findViewHolder(View view);
	/**
	 * 填充view
	 * @param position
	 * @param item
	 * @param holder
	 */
	protected abstract void setViewDisplay(int position,T item,V holder);
	/**
	 * view的按钮
	 * @param position
	 * @param item
	 * @param holder
	 */
	protected abstract void setClickListener(int position,T item,V holder);
	
	protected abstract int getLayoutId();
	public class ViewHolder
	{
		
	}

	/**
	 * 为避免快速点击添加。
	 * 
	 * 一般在onClick方法中使用，只有当返回false时，才执行按键点击操作。
	 */
	protected boolean ifPressed() {
		// 已点击，返回true
		if (ifPressed) {
			return true;
		}
		// 设置为已点击，400ms后，可重新点击
		ifPressed = true;
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				ifPressed = false;
			}
		}, 400); // 400ms 为允许按键相应的最端间隔时间
		return false;
	}

	// 设置监听
	public void setOnMyListener(MyListener<T> lis) {
		this.lis = lis;
	}

	// 选择
	public void selectItem(T item) {
		if (lis != null) {
			lis.onSelectItem(item);
		} else {
			LogUtil.e("MyAdapter --- lis为空, 无法回调！");
		}
	}
	
	

}
